package com.gxa.teax.admin.config;

import com.gxa.teax.admin.filters.LoginFilter;
import com.gxa.teax.admin.realm.AdminRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;
/**
 * shiro配置
 * @author wangpeng
 * @date 2022/07/19
 */
@Configuration
public class ShiroConfig {
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAap = new DefaultAdvisorAutoProxyCreator();
        defaultAap.setProxyTargetClass(true);
        return defaultAap;
    }

    @Autowired
    AdminRealm adminRealm;

    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(adminRealm);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> map = new HashMap<>(10);
        //过滤器,shiro提供了一个自定义过滤器的机制,改变登录不成功时的处理方式,不用跳转到login
        Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();
        //希望:返回给前端JSON
        filters.put("authc",new LoginFilter());
        //所有用户需要认证
        map.put("/**", "authc");
        //匿名访问的接口:anon表示匿名访问的过滤器,一般注册和登录可以匿名
        map.put("/**/register", "anon");
        map.put("/**/login", "anon");
        //swagger3资源放行
        map.put("/swagger-resources/**","anon");
        map.put("/webjars/**","anon");
        map.put("/v3/**","anon");
        map.put("/swagger-ui/**","anon");
        map.put("/doc.html/**","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

}
